using System;
using System.Collections.Generic;
using System.Text;

namespace Soyuz5.Utility.Web
{
    public class TimerCounter
    {
        Dictionary<string, DateTime> _list = new Dictionary<string, DateTime>();
        Dictionary<string, DateTime> List
        {
            get
            {
                if (_list == null)
                    _list = new Dictionary<string, DateTime>();
                return _list;
            }
        }

        TimeSpan _timeOut = new TimeSpan(0, 20, 0);
        public TimeSpan TimeOut
        {
            get
            {
                return _timeOut;
            }
            set
            {
                _timeOut = value;
            }
        }

        void Scrub()
        {
            lock (List)
            {
                List<string> keysToDelete = new List<string>();

                foreach (string key in List.Keys)
                {
                    if (List[key].AddTicks(_timeOut.Ticks) < DateTime.Now)
                    {
                        keysToDelete.Add(key);
                    }
                }

                foreach (string key in keysToDelete)
                {
                    List.Remove(key);
                }
            }
        }

        public void Add(string key)
        {
            lock (List)
            {
                List[key] = DateTime.Now;
            }
            Scrub();
        }

        public void Remove(string key)
        {
            lock (List)
            {
                List.Remove(key);
            }
            Scrub();
        }

        public int Count
        {
            get
            {
                Scrub();
                return List.Count;
            }
        }
    }
}
